package com.ruoyi.crop.controller;


import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.crop.api.domain.City;
import com.ruoyi.crop.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static com.ruoyi.common.core.web.domain.AjaxResult.success;

@RestController
@RequestMapping("city")
public class CityController {
    @Autowired
    CityService cityService;
    @Autowired
    HttpServletResponse response;
    @Autowired
    RedisTemplate redisTemplate;
    @PostConstruct
    public void init(){
        List<City> nodeList = cityService.list();
        redisTemplate.opsForValue().set("cityList",nodeList);
    }

    @RequestMapping("cityMenu")
    public AjaxResult cityMenu(){
        List<City>  nodeList = (List<City>) redisTemplate.opsForValue().get("cityList");
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        //转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> treeNodes = TreeUtil.<City, String>build(nodeList, "1", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getCityId()+"");
                    tree.setName(treeNode.getCityname());
                    tree.setParentId(treeNode.getPid()+"");
                });
        return success(treeNodes);
    }




}
